<template>
	<view>
		<view class="goods-list">
			<view v-for="(item, index) in goodsList" :key="index" @click="gotoDetail(item)">
				<my-goods :goods="item"></my-goods>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//请求的参数对象
				queryObj: {
					//查询的关键词
					query: '',
					//商品分类 id
					cid: '',
					//页数
					pagenum: 1,
					//每页显示多少条数据
					pageList: 18
				},
				// 商品列表的数据
				goodsList: [],
				// 总数据
				total: 0,
				// 判断是否正在请求数据，节流阀
				isloading: false
				
			};
		},
		onLoad(options) {
			this.queryObj.query = options.query || ''
			this.queryObj.cid = options.cid || ''
			this.getGoodsList()
		},
		methods: {
			async getGoodsList(stop) {
				// 打开节流阀
				this.isloading = true
				//发起请求
				const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
				// 关闭节流阀
				this.isloading = false
				//只要数据请求完毕，就立即调用 stop 回调函数
				stop && stop()
				if(res.meta.status !== 200) return uni.$showMsg()
				//为数据进行赋值
				this.goodsList = [...this.goodsList, ...res.message.goods]
				this.total = res.message.total
			},
			// 点击跳转到商品详情页
			gotoDetail(item){
				uni.navigateTo({
					url:`/subpkg/goods_detail/goods_detail?goods_id=${item.goods_id}`
				})
			}
		},
		
		//触底事件
		onReachBottom() {
			if(this.queryObj.pagenum * this.queryObj.pageList >= this.total) return uni.$showMsg('数据加载完毕！')
			//判断是否在请求其他数据，如果isloading为true，则不发起请求
			if(this.isloading) return 
			this.queryObj.pagenum += 1
			this.getGoodsList()
		},
		//下拉刷新事件
		onPullDownRefresh() {
			//重置关键数据
			this.queryObj.pagenum = 1
			this.total = 0
			this.isloading = false
			this.goodsList = []
			//重新发起请求
			this.getGoodsList(() => uni.stopPullDownRefresh())
		}
	}
</script>

<style lang="scss">

</style>
